<template>
  <div class="app-container">
    <el-row :gutter="10" class="mb8">
      <!--      <el-col :span="1.5">
              <el-button
                type="primary"
                plain
                icon="el-icon-plus"
                size="mini"
                @click="handleAdd"
                v-hasPermi="['teaching:design:add']"
              >新增</el-button>
            </el-col>-->
      <!--      <el-col :span="1.5">
              <el-button
                type="success"
                plain
                icon="el-icon-edit"
                size="mini"
                :disabled="single"
                @click="handleUpdate"
                v-hasPermi="['teaching:design:edit']"
              >修改</el-button>
            </el-col>
            <el-col :span="1.5">
              <el-button
                type="danger"
                plain
                icon="el-icon-delete"
                size="mini"
                :disabled="multiple"
                @click="handleDelete"
                v-hasPermi="['teaching:design:remove']"
              >删除</el-button>
            </el-col>-->
      <right-toolbar :showSearch="showSearch" @queryTable="getList"></right-toolbar>
    </el-row>
    <!--  -->
    <el-table v-loading="loading" :data="sys_stage" @selection-change="handleSelectionChange">
      <el-table-column type="selection" width="55" align="center"/>
      <el-table-column label="ID" align="center" prop="value"/>
      <el-table-column label="阶段" align="center" prop="label"/>
      <el-table-column label="操作" align="center" class-name="small-padding fixed-width">
        <template #default="scope">
          <el-button
              size="mini"
              type="text"
              icon="el-icon-edit"
              @click="handleUpdate(scope.row)"
              v-hasPermi="['teaching:design:edit']"
          >设计课程
          </el-button>
          <!--          <el-button
                      size="mini"
                      type="text"
                      icon="el-icon-delete"
                      @click="handleDelete(scope.row)"
                      v-hasPermi="['teaching:design:remove']"
                    >删除</el-button>-->
        </template>
      </el-table-column>
    </el-table>

    <pagination
        :page-sizes="[200,500]"
        :page-size="200"
        v-show="total>0"
        :total="total"
        v-model:page="queryParams.pageNum"
        v-model:limit="queryParams.pageSize"
        @pagination="getList"
    />

    <!-- 添加或修改课程设计对话框 -->
    <el-dialog :title="title" fullscreen v-model="open" width="500px" append-to-body>
      <el-form ref="formRef" :model="form" :rules="rules" label-width="80px">

        <el-form-item label="阶段" prop="stage">
          <el-select v-model="form.stage" placeholder="请选择阶段" :disabled="title=='修改课程设计'">
            <el-option
                v-for="dict in sys_stage"
                :key="dict.value"
                :label="dict.label"
                :value="dict.value"
            ></el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="课程天数">
          <el-input v-model="courseDesignList.length" :disabled="courseDesignList.length>0"/>
        </el-form-item>

        <el-divider></el-divider>
        <el-form-item :label="'第'+(i+1)+'天'" v-for="(cd,i) in courseDesignList" :key="i" ref="itemRefs" :id="(i)"
                      class="dragClass">
          <el-col span="14">
            <el-input v-model="cd.courseContent" :ref="'input-'+i"/>
          </el-col>
          <el-col span="2">
          </el-col>
          <el-col span="10">
            <el-button class="drag-btn" icon="el-icon-sort" :ref="'btn-'+i" :value="'btn-'+i" draggable="true"
                       style="height: 32px;width: 46px">
              <el-icon>
                <Sort/>
              </el-icon>
            </el-button>
            <el-button @click="addCourseDesign(i)" size="small" style="height: 32px;width: 46px">
              <el-icon>
                <Plus/>
              </el-icon>
            </el-button>
            <el-button @click="subCourseDesign(i)" size="small" style="height: 32px;width: 46px">
              <el-icon>
                <Minus/>
              </el-icon>
            </el-button>
            <el-button @click="handleRelatedInterview(cd)" v-if="cd.id" size="small" style="height: 32px">
              <el-icon>
                <Paperclip/>
              </el-icon>
              <span>自动关联面试题</span>
            </el-button>
          </el-col>
        </el-form-item>
        <el-divider></el-divider>
        <el-form-item>
          <el-col span="2">
            <el-input
                type="text"
                placeholder="天数"
                v-model="num"
                maxlength="2"
                show-word-limit
            ></el-input>
          </el-col>
          <el-col span="6">
            <el-button type="primary" icon="el-icon-finished" @click="batchAddCourseDesign">批量新增</el-button>
            <el-button type="danger" @click="resetCourseDesign" plain>还原</el-button>
          </el-col>
        </el-form-item>
      </el-form>
      <template #footer>
        <div class="dialog-footer">
          <el-button type="primary" @click="submitForm">确 定</el-button>
          <el-button @click="cancel">取 消</el-button>
        </div>
      </template>
    </el-dialog>

    <el-drawer
        size="60%"
        title="关联面试题"
        :visible="drawer"
        :direction="direction"
        :before-close="handleClose">
      <el-form :label-position="labelPosition" @submit.prevent label-width="10px" :model="formLabelAlign">
        <el-form-item label="">
          <el-checkbox-group v-model="selectedKeyWords" @change="handleSelectedKeywords">
            <el-checkbox :label="keyword" v-for="keyword in keywords" :key="keyword"></el-checkbox>
          </el-checkbox-group>
          <el-input v-model="newKeyWord" style="width: 50%" placeholder="关键字"
                    @keyup.enter="handleAddKeyWord"></el-input>
          <el-button
              size="medium"
              type="primary"
              style="width:10%;"
              @click="handleAddKeyWord"
          >
            <span>新增</span>
          </el-button>
        </el-form-item>
        <el-divider></el-divider>
        <el-form-item label="">
          <el-table
              ref="multipleTableRef"
              :data="relatedInterviewList"
              tooltip-effect="dark"
              style="width: 100%"
              @selection-change="handleRelatedInterviewSelectionChange">
            <el-table-column
                type="selection"
                width="55">
            </el-table-column>
            <el-table-column
                label="问题"
            >
              <template #default="scope">{{ scope.row.question }}</template>
            </el-table-column>
          </el-table>
        </el-form-item>
        <el-form-item>
          <el-button type="primary" @click="handleRelatedInteview">保存</el-button>
        </el-form-item>
      </el-form>

    </el-drawer>
  </div>
</template>

<script setup>
import {ref, reactive, onMounted, nextTick} from 'vue';
import {
  listCourse_design,
  getCourse_design,
  delCourse_design,
  updateCourse_design,
  getStageCourse_design,
  updateBatchCourse_design
} from "@/api/teaching/course_design";
import {queryRelatedInterview, queryRelatedInterviewByKeywords, saveRelatedInterview} from "@/api/teaching/interview";
// 引入
import draggable from "vuedraggable";
import {ElMessageBox, ElMessage} from 'element-plus';
import {Sort, Plus, Minus, Paperclip} from '@element-plus/icons-vue';

// 定义响应式数据
const {proxy} = getCurrentInstance()
const {sys_stage} = proxy.useDict('sys_stage')


const relatedInterviewIdList = ref([]);
const newKeyWord = ref("");
const selectedKeyWords = ref([]);
const keywords = ref([]);
const selectedCourseDesign = ref(null);
const selectedInterviewIdList = ref([]);
const relatedInterviewList = ref([]);
const drawer = ref(false);
const direction = ref('rtl');
const num = ref(1);
const bakCourseDesignList = ref([]);
const courseDesignList = ref([]);
const loading = ref(true);
const ids = ref([]);
const single = ref(true);
const multiple = ref(true);
const showSearch = ref(true);
const total = ref(0);
const designList = ref([]);
const title = ref("");
const open = ref(false);
const dict = ref({type: {sys_stage: []}});

// 查询参数
const queryParams = reactive({
  pageNum: 1,
  pageSize: 50,
  courseContent: null,
  courseId: null,
  day: null,
  stage: null,
  teacher: null,
  remarks: null
});

// 表单参数
const form = reactive({});

// 表单校验规则
const rules = {
  courseContent: [
    {required: true, message: "课程内容不能为空", trigger: "blur"}
  ],
  courseId: [
    {required: true, message: "课程ID不能为空", trigger: "blur"}
  ],
  day: [
    {required: true, message: "第几天不能为空", trigger: "blur"}
  ],
  stage: [
    {required: true, message: "阶段不能为空", trigger: "change"}
  ],
  teacher: [
    {required: true, message: "授课老师不能为空", trigger: "blur"}
  ],
  remarks: [
    {required: true, message: "备注信息不能为空", trigger: "blur"}
  ]
};

const dragItem = ref(null);
const formRef = ref(null);
const multipleTableRef = ref(null);
const labelPosition = ref('right');
const formLabelAlign = reactive({});

// 组件挂载时执行
onMounted(() => {
  getList();
});

//新增关键字
function handleAddKeyWord() {
  if (!newKeyWord.value) {
    return;
  }
  if (keywords.value.includes(newKeyWord.value)) {
    return;
  }

  keywords.value.push(newKeyWord.value);
  handleSelectedKeywords();
}

//根据选中关键字重新获取面试题
function handleSelectedKeywords() {
  if (!selectedKeyWords.value || selectedKeyWords.value.length === 0) {
    relatedInterviewList.value = [];
    return;
  }

  queryRelatedInterviewByKeywords(selectedKeyWords.value).then(response => {
    // 确保数据存在
    const responseData = response.data || {};
    relatedInterviewList.value = responseData || [];
  }).catch(error => {
    ElMessage.error("根据关键字查询面试题失败: " + error.message);
  });
}

function handleRelatedInteview() {
  console.log("准备保存关联关系:", {
    courseDesignId: selectedCourseDesign.value.id,
    interviewIds: selectedInterviewIdList.value
  });

  if (!selectedInterviewIdList.value || selectedInterviewIdList.value.length === 0) {
    ElMessage.error("至少选中一个面试题");
    return;
  }

  if (!selectedCourseDesign.value.id) {
    ElMessage.error("请先保存课程设计后再试");
    return;
  }

  // 显示加载提示
  const loading = ElLoading.service({
    lock: true,
    text: '保存中...',
    background: 'rgba(0, 0, 0, 0.7)'
  });

  // 保存关联关系
  saveRelatedInterview(selectedCourseDesign.value.id, selectedInterviewIdList.value)
      .then(response => {
        console.log("保存成功:", response);
        ElMessage.success("关联面试题成功");
        drawer.value = false;

        // 重新查询关联信息以更新界面
        handleRelatedInterview(selectedCourseDesign.value);
      })
      .catch(error => {
        console.error("保存失败:", error);
        ElMessage.error("关联面试题失败: " + (error.message || "未知错误"));
      })
      .finally(() => {
        loading.close();
      });
}

function handleRelatedInterviewSelectionChange(selectedInterviewList) {
  selectedInterviewIdList.value = selectedInterviewList.map((interview) => interview.id);
}

//查询关联面试题
function handleRelatedInterview(courseDesign) {
  keywords.value = [];
  selectedKeyWords.value = [];
  selectedCourseDesign.value = courseDesign;
  drawer.value = true;
  relatedInterviewList.value = [];
  selectedInterviewIdList.value = [];

  // 查询关联面试题
  queryRelatedInterview(courseDesign.id, courseDesign.courseContent)
      .then(response => {
        const data = response.data || {};

        // 处理高相关度面试题
        relatedInterviewList.value = Array.isArray(data.highInterviewList) ? data.highInterviewList : [];

        // 处理关键词
        keywords.value = Array.isArray(data.keywords) ? data.keywords : [];
        selectedKeyWords.value = Array.isArray(data.keywords) ? data.keywords : [];

        // 处理已关联的面试题ID
        relatedInterviewIdList.value = Array.isArray(data.relatedInterviewIdList) ? data.relatedInterviewIdList : [];

        // 设置已选中的面试题
        nextTick(() => {
          if (relatedInterviewIdList.value && relatedInterviewIdList.value.length > 0) {
            relatedInterviewIdList.value.forEach(id => {
              const item = relatedInterviewList.value.find(ri => ri.id === id);
              if (item) {
                multipleTableRef.value.toggleRowSelection(item);
              }
            });
          }
        });
      })
      .catch(error => {
        ElMessage.error("查询关联面试题失败: " + (error.response?.data?.msg || error.message));
      });
}

function handleClose(done) {
  ElMessageBox.confirm('确认关闭？未保存的关联关系将丢失')
      .then(_ => {
        // 关闭前清空相关数据
        keywords.value = [];
        selectedKeyWords.value = [];
        relatedInterviewList.value = [];
        selectedInterviewIdList.value = [];
        selectedCourseDesign.value = null;
        done();
      })
      .catch(_ => {
      });
}

function resetCourseDesign() {
  courseDesignList.value = [];
  let newCourseDesignList = JSON.parse(JSON.stringify(bakCourseDesignList.value));
  for (let i = 0; i < newCourseDesignList.length; i++) {
    let temp = newCourseDesignList[i];
    courseDesignList.value[i] = temp;
  }
}

function downward(i) {
  let temp = courseDesignList.value[i + 1];
  courseDesignList.value[i + 1] = courseDesignList.value[i];
  courseDesignList.value[i] = temp;
}

function upward(i) {
  let temp = courseDesignList.value[i - 1];
  courseDesignList.value[i - 1] = courseDesignList.value[i];
  courseDesignList.value[i] = temp;
}

function batchAddCourseDesign() {
  if (!num.value || num.value === 0) {
    ElMessage.error("天数必须大于0");
    return;
  }
  for (let i = 0; i < num.value; i++) {
    addCourseDesign(courseDesignList.value.length);
  }
  initDrag();
}

function subCourseDesign(i) {
  courseDesignList.value.splice(i, 1);
  initDrag();
}

function addCourseDesign(i) {
  //修改标题为新增
  title.value = "新增课程设计";
  let courseDesign = {
    "courseContent": "",
    "day": i + 1,
    "stage": form.stage,
    "remarks": ""
  }
  //courseDesignList.value.push(courseDesign);
  courseDesignList.value.splice(i + 1, 0, courseDesign);
  initDrag(i + 1);
}

/** 查询课程设计列表 */
function getList() {
  loading.value = true;
  listCourse_design(queryParams).then(response => {
    designList.value = response.rows;
    total.value = response.total;
    loading.value = false;
  });
}

// 取消按钮
function cancel() {
  open.value = false;
  reset();
}

// 表单重置
function reset() {
  Object.assign(form, {
    stage: null,
    days: 40
  });
  // resetForm("form");
  bakCourseDesignList.value = [];
}

/** 搜索按钮操作 */
function handleQuery() {
  queryParams.pageNum = 1;
  getList();
}

/** 重置按钮操作 */
function resetQuery() {
  // resetForm("queryForm");
  handleQuery();
}

// 多选框选中数据
function handleSelectionChange(selection) {
  ids.value = selection.map(item => item.id)
  single.value = selection.length !== 1
  multiple.value = !selection.length
}

/** 新增按钮操作 */
function handleAdd() {
  reset();
  open.value = true;
  title.value = "添加课程设计";
}

/** 修改按钮操作 */
function handleUpdate(row) {
  reset();
  const stageId = row.value
  console.log(stageId)
  // getStageCourse(stageId).then(response => {
  getStageCourse_design(stageId).then(response => {

    form.stage = row.value;
    courseDesignList.value = response.data;
    if (courseDesignList.value && courseDesignList.value.length === 0) {
      addCourseDesign(0)
    } else {
      title.value = "修改课程设计";
    }
    open.value = true;
    bakCourseDesignList.value = JSON.parse(JSON.stringify(courseDesignList.value));
    initDrag();
  });
}

function onDragstart(event) {
  // 设置数据传输并将当前拖动的元素的ID传递给数据
  let index = event.target.value.split('-')[1];
  dragItem.value = document.getElementById(index);
  if (dragItem.value == null || dragItem.value.id == null) {
    ElMessage.warning("重新选择拖动元素");
    return;
  }
  event.dataTransfer.setData('text/plain', dragItem.value.id);
}

function onDragover(event) {
  // 防止默认操作
  event.preventDefault();
  // 检查拖动的元素是否超出了允许的位置
  if (event.currentTarget == null) {
    return;
  }
  if (event.currentTarget.id == null) {
    return;
  }
  if (dragItem.value == null) {
    return;
  }
  //isSameIndex
  if (dragItem.value.id == event.currentTarget.id) {
    event.dataTransfer.dropEffect = 'none';
  } else {
    event.dataTransfer.dropEffect = 'move';
  }
}

function onDragenter(event) {
  // 防止默认操作
  event.preventDefault();
}

function onDragleave(event) {
}

function onDrop(event) {
  // 拖动元素下标
  const currentIndex = event.dataTransfer.getData('text/plain');
  // 目标元素下标
  const targetIndex = parseInt(event.currentTarget.id);
  // 交换拖动元素和放置目标的位置
  // const temp = courseDesignList.value[dragIndex];
  // courseDesignList.value[dragIndex] = courseDesignList.value[dropIndex]
  // courseDesignList.value[dropIndex] = temp

  //delete and get currentElement in a array
  let delArray = courseDesignList.value.splice(currentIndex, 1);
  courseDesignList.value.splice(targetIndex, 0, delArray[0]);
}

function onDragend(event) {
}

//初始化新增表单项拖动功能
function initDrag() {
  // 在下一个 DOM 更新周期中调用方法
  nextTick(() => {
    // 获取所有的 itemRefs 引用
    // const itemRefs = this.$refs.itemRefs;
    const itemRefs = document.querySelectorAll('.dragClass');
    itemRefs.forEach(item => {
      item.removeEventListener('dragstart', onDragstart);
      item.removeEventListener('dragover', onDragover);
      item.removeEventListener('dragenter', onDragenter);
      item.removeEventListener('dragleave', onDragleave);
      item.removeEventListener('drop', onDrop);

      item.addEventListener('dragstart', onDragstart);
      item.addEventListener('dragover', onDragover);
      item.addEventListener('dragenter', onDragenter);
      item.addEventListener('dragleave', onDragleave);
      item.addEventListener('drop', onDrop);
    })
  });
}

/** 提交按钮 */
function submitForm() {
  //重新计算day数
  if (courseDesignList.value) {
    for (let i = 0; i < courseDesignList.value.length; i++) {
      let cd = courseDesignList.value[i];
      if (!cd.courseContent) {
        ElMessage.error("课程内容不能为空")
        return;
      }
      cd.day = i + 1;
    }
    updateBatchCourse_design({
      stage: form.stage,
      courseList: courseDesignList.value
    }).then(response => {
      ElMessage.success("修改成功");
      open.value = false;
      getList();
    });
  } else {
    ElMessage.warning("至少有一个课程设计")
  }
}

/** 删除按钮操作 */
function handleDelete(row) {
  const ids = row.id || ids.value;
  ElMessageBox.confirm('是否确认删除课程设计编号为"' + ids + '"的数据项？').then(function () {
    return delCourse_design(ids);
  }).then(() => {
    getList();
    ElMessage.success("删除成功");
  }).catch(() => {
  });
}

/** 导出按钮操作 */
function handleExport() {
  // download('teaching/design/export', {
  //   ...queryParams
  // }, `design_${new Date().getTime()}.xlsx`)
}

defineOptions({
  name: "Course_design",
  dicts: ['sys_stage']
});
</script>
